local mqtt_cli = {
    _evt_hash = {},
    msgfunc_ = function() end ,
    onsuc_ = function() end , 
    failunc_ = function() end 
}
--==================================
--default params
local mqtt = mqtt
local crypto = crypto
local encoder = encoder
local ALI_MQTT = require("ihome.constant").ALI_MQTT
local INSTANCE_ID = ALI_MQTT["INSTANCE_ID"]
local BROKER_URL = ALI_MQTT["BROKER_URL"]
local ACCESS_KEY = ALI_MQTT["ACCESS_KEY"]
local SECRET_KEY = ALI_MQTT["SECRET_KEY"]
local CLIENT_ID = ALI_MQTT["GID"]
--==================================

function mqtt_cli:reg_msg(msg, func)
    if type(msg) ~= "string" then return end 
    if type(func) ~= "function" then return end 
    if (self._evt_hash[msg]) ~= "table" then 
        self._evt_hash[msg] = {}
    end
    table.insert(self._evt_hash[msg], func)
    return self
end

function mqtt_cli:__reg_def(cli)
    cli:on("connect", function(client) 
        self._is_con = true
        self.onfunc_()
    end)
    cli:on("connfail", function(client, reason)
        self._is_con = nil 
        print ("connection failed", reason) 
        self.failunc_(reason)
    end)
    cli:on("message", function(msg)
        if (self._evt_hash[msg]) ~= "table" then 
            return self._evt_hash[msg]
        end
        if #self._evt_hash > 0  then 
            for _, handler in ipairs(self._evt_hash) do 
                handler()
            end
        end
    end)
    return self
end

function mqtt_cli:__conenct()
    print("mqtt_cli start conenct...")
    local user = gen_username() 
    local pwd = gen_pwd()
    print(gen_username(), gen_pwd(), "-->>usr, pwd")
    local cli = mqtt.Client(CLIENT_ID, 120, user, pwd)
    cli:lwt("/lwt", "offline", 0, 0)
    --callfunc logic move to event dispatch
    cli:connect(BROKER_URL, 1883, false, function()
        print("success")
    end, 
    function(client, reason)
        print(reason, "-->>failed!")
    end)
    print("wait con...")
    -- self:__reg_def(cli)
    return self
end

function mqtt_cli:on(onfunc)
    if type(onfunc) == "function" then 
        self.onfunc_ = onfunc
    end
    self:__conenct()
    return self
end

function mqtt_cli:fail(failfunc)
    if type(failfunc) == "function" then 
        self.failunc_ = failfunc
    end
    return self
end

return mqtt_cli
